package com.efast.cafe.framework.interceptor;

import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.efast.cafe.util.ConfigUtil;

import net.sf.json.JSONObject;
@Component
public class FileUploadInterceptor extends HandlerInterceptorAdapter{

	private int maxUploadSize=Integer.parseInt(ConfigUtil.getValue("cafe.upload.maxUploadSize"));
	
	private String suffixs=ConfigUtil.getValue("cafe.upload.suffixs");

	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		//判断是否文件上传
        if(request!=null && ServletFileUpload.isMultipartContent(request)) {
        	response.setCharacterEncoding("UTF-8"); 
   		 	response.setContentType("application/json; charset=utf-8");
            ServletRequestContext ctx = new ServletRequestContext(request);
            //获取上传文件尺寸大小
            long requestSize = ctx.getContentLength();
            if (requestSize > maxUploadSize) {
                //当上传文件大小超过指定大小限制后，模拟抛出MaxUploadSizeExceededException异常
        //        throw new MaxUploadSizeExceededException(maxUploadSize);
            	System.out.println("文件大小超出限制...");
            	JSONObject jo = new JSONObject();
            	jo.put("errorCode", "maxUploadSizeException");
            	jo.put("maxUploadSize", maxUploadSize/1024/1024+"M");
            	response.getWriter().print(jo.toString());
                return false;
            }
            MultipartHttpServletRequest  multipartRequest=(MultipartHttpServletRequest) request;
            Map<String, MultipartFile> files= multipartRequest.getFileMap();
            Iterator<String> iterator = files.keySet().iterator();  
            while (iterator.hasNext()) {  
            	String formKey = (String) iterator.next();
            	 MultipartFile multipartFile = multipartRequest.getFile(formKey); 
            	 if (!StringUtils.isEmpty(multipartFile.getOriginalFilename())) {  
            		 String filename = multipartFile.getOriginalFilename(); 
            		 if(!checkFile(filename)){
            			 System.out.println("文件类型不正确...");
            			 JSONObject jo = new JSONObject();
                     	jo.put("errorCode", "suffixException");
                     	jo.put("fileName", filename);
                     	jo.put("suffixs", suffixs);
                     	response.getWriter().print(jo.toString());
            			 return false;
            		 }
            	 }
            }
        }
        return true;
    }
	
	 private  boolean checkFile(String fileName){  
	        boolean flag=false;  
	        //获取文件后缀  
	        String suffix=fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());  
	          
	        if(suffixs.contains(suffix.trim().toLowerCase())){  
	            flag=true;  
	        }  
	        return flag;  
	    }  
	
	
	public void setSuffixs(String suffixs) {
		this.suffixs = suffixs;
	}


	public void setMaxUploadSize(int maxUploadSize) {
		this.maxUploadSize = maxUploadSize;
	}
	
}
